// pages/zhuce/zhuce.js
import request from '../../utils/http.js'
const app = getApp()
const defaultAvatarUrl = 'https://insurancecard.oneplusyang.com/20240227163110d366a6d21a6c478b89e6c6dffd6b12b7.png'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: '',
    codeIsUse: false,

    personId: 0,
    tjr_id: 0,
    phone: '',
    name: '',
    huiYuanRole:0,//1会员 2会长 3总裁
    shopName:'',
    JKQName:'',

    shangJiNiCheng: '',
    shangJiTouXiangUrl: '',
    shangJiIsHuiYuan: '',



    userName: '', //联系人
    provinceName: '', //省
    cityName: '',
    countyName: '', //区
    nationalCode: '',
    postalCode: '',
    detailInfo: '', //详细地址
    telNumber: '', //联系电话



    IsLogin: false,
    isAction: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('dd')
    var that = this
    wx.login({
      success: res => {
        that.setData({
          code: res.code
        })
      }
    })

    that.setData({
      tjr_id: wx.getStorageSync(app.globalData.TJR_ID),
      dianPuId: wx.getStorageSync(app.globalData.SHOPID),
      IsLogin: wx.getStorageSync(app.globalData.LOGINSTATUS),
      phone: wx.getStorageSync(app.globalData.LOGINSTATUS)?wx.getStorageSync(app.globalData.PHONENUMBER):'',
      personId: wx.getStorageSync(app.globalData.PERSON_ID),
      shopName: wx.getStorageSync(app.globalData.ShopName),
      JKQName:wx.getStorageSync(app.globalData.JKQName),

      userName: wx.getStorageSync(app.globalData.USERNAME), //联系人
      provinceName: wx.getStorageSync(app.globalData.PROVINCENAME), //省
      cityName: wx.getStorageSync(app.globalData.CITYNAME),
      countyName: wx.getStorageSync(app.globalData.COUNTYNAME), //区
      nationalCode: wx.getStorageSync(app.globalData.NATIONALCODE),
      postalCode: wx.getStorageSync(app.globalData.POSTALCODE),
      detailInfo: wx.getStorageSync(app.globalData.DETAILINFO), //详细地址
      telNumber: wx.getStorageSync(app.globalData.TELNUMBER), //联系电话
    })

    if(that.data.IsLogin){
      that.gethyInfo()
    }else{
      if (that.data.tjr_id > 0) {
        that.getTJRInfo()
      }

    }

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },


  //获取会员信息
  gethyInfo: function () {
    var that = this
    let data = {
      dianPuId: that.data.dianPuId
    }
    request.get('person/getPersonJianKangHui', data, res => {

      console.log("会员信息:" + JSON.stringify(res.data))
      // wx.setStorageSync(app.globalData.VerIndex, res.data.status)
      that.setData({
        
        phone:res.data.phone,
        name:res.data.name,
        huiYuanRole:res.data.huiYuanRole,
        shangJiNiCheng:res.data.shangJiNiCheng,
        shangJiTouXiangUrl: res.data.shangJiTouXiangUrl,
        tjr_id:res.data.huiYuanRole>0?res.data.jianKangHuiShangJiId:wx.getStorageSync(app.globalData.TJR_ID),
      })

      if(res.data.huiYuanRole==0){
        if (that.data.tjr_id > 0) {
          that.getTJRInfo()
        }
      }
      that.isAction();

    }, err => {

    })
  },

  getTJRInfo() {
    var that = this

    var data = {
      personId: that.data.tjr_id,
      dianPuId: that.data.dianPuId,
    }

    request.get('person/getOneNiChengByPersonId', data, res => {

      wx.hideLoading()
      // console.log("推荐人:" + JSON.stringify(res.data))
      that.setData({
        shangJiNiCheng: res.data.xingMing != '' ? res.data.xingMing : res.data.niCheng,
        shangJiTouXiangUrl: res.data.touXiangUrl,
        shangJiIsHuiYuan: res.data.isHuiYuan == 1 ? '(会员)' : '(非会员)',
      })

      that.isAction();

    })
  },


  //V3.0 获取手机号码
  getPhoneNumber: function (e) {


    var that = this
    if (e.detail.errMsg == "getPhoneNumber:ok") { //允许
      that.decryptPhone(e);
    } else { //拒绝
      wx.showToast({
        title: "请授权！！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }
  },

  //V3.0 解密手机号码
  decryptPhone: function (e) {

    wx.showLoading({
      title: '解析中...',
      mask: true
    })

    var that = this;
    let code = that.data.code;
    let iv = e.detail.iv;
    let encryptedData = e.detail.encryptedData;

    wx.request({
      url: app.globalData.base_url + 'resource/getWXPhoneDirect',
      data: {
        iv: iv,
        js_code: code,
        encrypted: encryptedData,
        tuiJianRenId: that.data.tjr_id,
        dianPuId: that.data.dianPuId
      },
      success: function (res) {
        // console.log("解密手机号码:" + JSON.stringify(res.data))
        wx.hideLoading();
        if (res.data.purePhoneNumber == '' || res.data.status == 500) {

          wx.showModal({
            title: "解析异常！",
            content: "请点右上角‘重新进入小程序’重试",
            showCancel: false,
            success(res) {
              that.setData({
                codeIsUse: true
              })
            }
          })


        } else {
          wx.setStorageSync(app.globalData.OPENID, res.data.openId)
          wx.setStorageSync(app.globalData.PERSON_ID, res.data.personId)
          wx.setStorageSync(app.globalData.TOKEN, res.data.token)
          wx.setStorageSync(app.globalData.PHONENUMBER, res.data.purePhoneNumber)
          wx.setStorageSync(app.globalData.LOGINSTATUS, true)
          wx.setStorageSync(app.globalData.NiCheng, res.data.niCheng)
          wx.setStorageSync(app.globalData.TouXiang, res.data.touXiangUrl)

          that.setData({
            phone: res.data.purePhoneNumber,
            personId: res.data.personId,
            IsLogin: true,
            codeIsUse: true,
          })

          that.isAction();

        }
      },
      fail: function (err) {
        wx.hideLoading();
        that.setData({
          IsLogin: false
        })
        wx.showToast({
          title: '获取数据失败,请检查网络', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {

      }
    })
  },


  //支付注册
  zhucePay: function () {
    var that = this

    if (that.data.personId < 1) {
      wx.showToast({
        title: "请先授权获取手机号！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
        complete: function () {
          that.setData({
            isClick: false
          })
        }
      })
    } else if (that.data.isClick) {
      wx.showToast({
        title: "注册处理中，请勿重复提交！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
      return

    } else {

      if (that.data.isAction) {
        that.setData({ //避免重复
          isClick: true
        })
        wx.showLoading({
          title: '注册中...',
          mask: true
        })

        let data = {
          openId: wx.getStorageSync(app.globalData.OPENID),
          dianPuId: that.data.dianPuId,
          // zhongXinChanPinId: that.data.zhongXinChanPinId,
          jianKangHuiShangJiId: that.data.tjr_id,
          name: that.data.name,
          // wxUserName: that.data.userName,
          // wxPostalCode: that.data.postalCode,
          // wxProvinceName: that.data.provinceName,
          // wxCityName: that.data.cityName,
          // wxCountyName: that.data.countyName,
          // wxDetailInfo: that.data.detailInfo,
          // wxNationalCode: that.data.nationalCode,
          // wxTelNumber: that.data.telNumber,
        }

        request.get('OrderForm20231109/addHuiYuan', data, res => {

          wx.hideLoading()
          // console.log("注册:" + JSON.stringify(res.data))
          if (res.data.status == 1) {
            wx.requestPayment({
              timeStamp: res.data.map.timeStamp,
              nonceStr: res.data.map.nonce_str,
              package: 'prepay_id=' + res.data.map.prepay_id,
              signType: 'MD5',
              paySign: res.data.map.paySign,
              success: function (ress) {

                wx.showModal({
                  title: '注册成功',
                  icon: "none",
                  content: '恭喜您成为健康圈会员！',
                  duration: 1000,
                  showCancel:false,
                  mask: false,
                  success (res) {
                    if (res.confirm) {
                      wx.navigateBack({
                        delta: 1,
                      })
                    } else if (res.cancel) {
                      console.log('用户点击取消')
                    }
                  }
                })

              },
              fail: function (ress) {
                wx.showToast({
                  title: "支付失败！", // 提示的内容
                  icon: "none", // 图标，默认success
                  duration: 1500, // 提示的延迟时间，默认1500
                  mask: false, // 是否显示透明蒙层，防止触摸穿透
                  complete: function () {

                    setTimeout(function () {
                      wx.navigateBack({
                        delta: 1,
                      })
                    }, 1000)

                  }
                })

                that.setData({
                  isClick: false
                })
              },
              complete: function (ress) {
                //console.log("payComplete:" + JSON.stringify(res.data))
              }
            });
            // that.zhifu(res.data.dingDanHao);
          } else { //订单生成失败

            wx.showToast({
              title: "订单生成失败！", // 提示的内容
              icon: "none", // 图标，默认success
              duration: 3000, // 提示的延迟时间，默认1500
              mask: false, // 是否显示透明蒙层，防止触摸穿透
              complete: function () {
                that.setData({
                  isClick: false
                })
              }
            })
          }

        })
      } else {
        wx.showToast({
          title: "请输入会员姓名、选择产品，以及收货地址！", // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
          complete: function () {

          }
        })
      }
    }
  },




  //修改姓名
  bindNameInput: function (e) {
    // console.log(e.detail.value)
    this.setData({
      name: e.detail.value
    })

    this.isAction();
  },




  isAction() {

    if (this.data.personId > 0 && this.data.phone!=""  && this.data.name != "") {
      this.setData({
        isAction: true
      })
    } else {
      this.setData({
        isAction: false
      })
    }
  },




  //虚拟支付
  zhifu: function (dingDanHao) {
    var that = this
    let data = {
      dingDanHao: dingDanHao,
    }
    request.get('OrderForm20231109/xiuNiZhiFu', data, res => {
      wx.hideLoading();

      wx.showModal({
        title: '注册成功',
        icon: "none",
        content: '恭喜您成为健康圈会员！',
        duration: 1000,
        showCancel:false,
        mask: false,
        success (res) {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1,
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })



    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

})